import json
from sqlalchemy import Result, select
from sqlalchemy.ext.asyncio import AsyncSession

from scaner.core.models import Rubricator, SearchOrder, ADS, User
from scaner.core.config.log_config import MyLogger
from . import schemas

main_logger = MyLogger("main")
logger = main_logger.getChild("scrap")  # type: ignore


async def create_rubricator(
    session: AsyncSession,
    rubricator: list[dict],
) -> dict:
    rubrics = Rubricator(rubrics=json.dumps(rubricator))

    session.add(rubrics)
    await session.commit()

    return {"result": "Success"}


async def get_last_rubricator(
    session: AsyncSession,
) -> list[dict] | None:
    stmt = select(Rubricator).order_by(Rubricator.created_at.desc()).limit(1)
    result: Result = await session.execute(stmt)
    data: Rubricator | None = result.scalars().first()

    if data:
        return json.loads(data.rubrics)

    return None


async def order_create(
    order_in: schemas.SearchOrderCreate,
    user: User,
    session: AsyncSession,
) -> SearchOrder:

    logger.info("Создание ордера")

    order = SearchOrder(**order_in.model_dump())
    order.user_id = user.id

    session.add(order)
    await session.commit()
    await session.refresh(order)

    return order


async def get_orders_for_current_user(
    user: User,
    session: AsyncSession,
) -> list[schemas.SearchOrderRead]:
    stmt = (
        select(SearchOrder)
        .where(SearchOrder.user == user)
        .order_by(SearchOrder.created_at.desc())
    )
    result: Result = await session.execute(stmt)
    orders = result.scalars().all()
    return list(orders) if orders else []


async def get_last_order(
    user_id: int,
    session: AsyncSession,
) -> SearchOrder | None:

    stmt = (
        select(SearchOrder)
        .where(SearchOrder.user_id == user_id)
        .order_by(SearchOrder.created_at.desc())
        .limit(1)
    )

    result: Result = await session.execute(stmt)
    data: SearchOrder | None = result.scalars().first()

    if data:
        return data

    return None


async def get_order_by_id(
    session: AsyncSession,
    id: int,
) -> SearchOrder | None:
    return await session.get(SearchOrder, id)


async def delete_order(
    order: SearchOrder,
    session: AsyncSession,
) -> None:
    await session.delete(order)
    await session.commit()


async def ads_create(
    ads_in: schemas.ADSDataCreate,
    session: AsyncSession,
) -> None:
    ads = ADS(**ads_in.model_dump())
    session.add(ads)
    await session.commit()


async def ads_create_all(
    data_in: list[schemas.ADSDataBase],
    session: AsyncSession,
) -> list[ADS]:

    ads: list[ADS] = []

    for ad in data_in:
        ads.append(ADS(**ad.model_dump()))  # type: ignore

    session.add_all(ads)
    await session.commit()
    await session.refresh(ads)
    return ads if ads else []


async def get_ads_by_order(
    order: SearchOrder,
    session: AsyncSession,
) -> list[ADS]:
    stmt = select(ADS).where(ADS.order_id == order.id).order_by(ADS.created_at.desc())
    result: Result = await session.execute(stmt)
    ads = result.scalars().all()
    return list(ads) if ads else []


async def delete_ads(
    ads: ADS,
    session: AsyncSession,
) -> None:
    await session.delete(ads)
    await session.commit()
